package com.af.robot.util.imp;

import com.af.robot.util.Manager;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.io.*;

@Component
public class TomcatManager extends Manager {
    @Override
    public boolean start(String path) {
        try {
            Runtime rt = Runtime.getRuntime();
            rt.exec("cmd.exe /c startup.bat",null,new File(path));
            return true;
        }catch (Exception e){
            return false;
        }
    }

    @Override
    public boolean stop(String port) {
        try{
            Runtime rt = Runtime.getRuntime();
            Process p = rt.exec("cmd.exe /c netstat -ano | findstr 0.0.0.0:"+port+" | findstr LISTENING ");
            InputStream inputStream =p.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream,"GBK"));
            String line=null;
            StringBuilder b=new StringBuilder();
            while ((line=br.readLine())!=null) {
                b.append(line).append("\n");
            }
            String back = b.toString().split("\n")[0];
            String[] detailed = back.split(" ");
            String killPid = detailed[detailed.length-1];
            rt.exec("cmd.exe /c taskkill -f -pid " + killPid);
            return true;
        } catch (IOException e) {
            return false;
        }
    }
}
